package com.jeeww.interceptor;

import java.io.Serializable;
import java.util.Date;

import org.apache.log4j.Logger;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.springframework.stereotype.Component;

import com.jeeww.utils.UserDetailUtils;

/**
 * Hiberate拦截器：实现创建人，创建时间，创建人名称自动注入; 修改人,修改时间,修改人名自动注入.
 */
@Component
public class CustomerHibernateInterceptor extends EmptyInterceptor {
    /**
     * log.
     */
    private static Logger logger = Logger.getLogger(CustomerHibernateInterceptor.class);
    /**
     * .
     */
    private static final long serialVersionUID = 1L;

    @Override
    public boolean onSave(final Object entity, final Serializable id, final Object[] state,
            final String[] propertyNames, final Type[] types) {
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("自动更新创建人，创建时间.");
            }
            // 添加数据
            for (int index = 0; index < propertyNames.length; index++) {
                /* 找到名为"创建时间"的属性 */
                if ("createDate".equals(propertyNames[index])) {
                    state[index] = new Date();
                    continue;
                } else if ("createUserId".equals(propertyNames[index])) { /* 找到名为"创建人"的属性 */
                    state[index] = UserDetailUtils.getUserDetail().getUserInfo().getUserId();
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public boolean onFlushDirty(final Object entity, final Serializable id, final Object[] currentState,
            final Object[] previousState, final String[] propertyNames, final Type[] types) {
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("自动更新修改人，修改时间.");
            }
            for (int index = 0; index < propertyNames.length; index++) {
                /* 找到名为"修改时间"的属性 */
                if ("updateDate".equals(propertyNames[index])) {
                    /* 使用拦截器将对象的"修改时间"属性赋上值 */
                    currentState[index] = new Date();
                    continue;
                } else if ("updateUserId".equals(propertyNames[index])) { /* 找到名为"修改人"的属性 */
                    /* 使用拦截器将对象的"修改人"属性赋上值 */
                    currentState[index] = UserDetailUtils.getUserDetail().getUserInfo().getUserId();
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}
